from django.db import connection

from libs.common import success
from libs.db import DB
from libs.form import Page


def fix_sell_count(request):
    page = 1
    size = 100
    row_num = 1
    with connection.cursor() as cursor:
        while row_num > 0:
            sql = 'SELECT * FROM (SELECT o.order_id,o.goods_id,o.goods_name,o.goods_price,SUM(ABS(o.sell_number)) sell_total,tg.`sell_count`,o.state,' \
                  'o.`offline_order_id`,o.order_type,o.`send_shop_id` FROM table_orders o LEFT JOIN table_goods tg ON tg.id=o.`goods_id` WHERE o.goods_id>0 AND ' \
                  'o.state IN (1,2,3,7) GROUP BY o.goods_id) t WHERE sell_count!=sell_total'
            page += 1
            offset = 0
            limit = ' limit {},{}'.format(offset, size)
            sql += limit
            db = DB('')
            goods_dh = DB('table_goods', conn=cursor)
            rows = db.query(sql)
            row_num = len(rows)
            print('page', page, row_num)
            for row in rows:
                goods_id = row.get('goods_id')
                new_sell_count = row.get('sell_total')
                goods_dh.update({'sell_count': new_sell_count}, {'id': goods_id})
    return success()


def cart_data(request):
    page_num = 1
    size = 100
    row_num = 1
    page = Page(page_num, size)
    goods_id_arr = []
    cls_map = {}
    with connection.cursor() as cursor:
        while row_num > 0:
            dh = DB('cs_carts', conn=cursor)
            rows = dh.page(page).find('*')
            row_num = len(rows)
            page_num += 1
            page.set_page(page_num)
            for row in rows:
                goods_id_arr.append(str(row.get('goods_id')))
            goods_id_set = set(goods_id_arr)
            if len(goods_id_set) > 0:
                dh = DB('table_goods', conn=cursor)
                rows = dh.find(['id', 'class_id'], {
                    'goods_id in ()'.format(','.join(goods_id_set)): None
                })
                for row in rows:
                    print(row)
                    goods_id = row.get('id')
                    cls_name = cls_map.get(goods_id, None)
                    if cls_name is None:
                        dh = DB('table_goods_class', conn=cursor)
                        cls_row = dh.one(['class_name'], {
                            'id': row.get('class_id')
                        })
                        cls_name = cls_row.get('class_name')
                        cls_map.update({goods_id: cls_name})
                        print(cls_name)
    return success()
